package com.lsk.mobile;

import com.alipay.api.AlipayApiException;
import com.alipay.api.response.AlipayFundTransToaccountTransferResponse;
import com.jfinal.aop.Before;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtom;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.plugin.redis.Cache;
import com.jfinal.plugin.redis.Redis;
import com.jfinal.weixin.sdk.api.PaymentApi;
import com.jfinal.weixin.sdk.api.RedPackApi;
import com.jfinal.weixin.sdk.kit.PaymentKit;
import com.lsk.api.ApiReturn;
import com.lsk.pc.PcService;
import com.lsk.util.*;
import org.apache.commons.lang.StringUtils;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Administrator on 2018/7/17 0017.
 */
public class MobileServices {

    Cache cache = Redis.use();

    public Record getWxConfigByOrgId(String orgId, int type) {
        String sql = "SELECT *from weixin_public_account_info where orgId='" + orgId + "' and type=" + type;
        Record record = Db.findFirstByCache("weixinConfig", MD5.md5(sql), sql);
        return record;
    }

    /**
     * 根据机构号查询商品列表
     *
     * @param orgId
     * @return
     */
    public List<Record> getCommodityList(String orgId, String unionId) {
        String element = getElementName(orgId, unionId);
        String sql = "SELECT id,name,imgPath,originalMoney," + element + " as money   from shop_commodity where orgId='" + orgId + "'";
        List<Record> recordList = Db.find(sql);
        for (int i = 0; i < recordList.size(); i++) {
            Record record = recordList.get(i);
            String id = record.getStr("id");
            List<Record> list = getCommodityImgs(id);
            record.remove("imgPath");
            record.set("imgPath", list);
            recordList.set(i, record);
        }
        return recordList;
    }

    /**
     * 根据商品Id获取图片列表
     *
     * @param commodityId
     * @return
     */
    public List<Record> getCommodityImgs(String commodityId) {
        String sql = "SELECT *from shop_commodity_imgpath where commodityId='" + commodityId + "'";
        List<Record> list = Db.find(sql);
        return list;
    }

    /**
     * 根据机构号，会员unionId等级得到商品价格对应字段
     */
    public String getElementName(String orgId, String unionId) {
        String sql = "SELECT  * from yx_member  where unionId='" + unionId + "' and orgId='" + orgId + "'";
        Record record = Db.findFirst(sql);
        String result = "money";
        if (record != null) {
            int grade = record.getInt("grade");
            if (grade == 1) {
                result = "oneMoney";
            } else if (grade == 2) {
                result = "twoMoney";
            } else if (grade == 3) {
                result = "threeMoney";
            } else if (grade == 4) {
                result = "fourMoney";
            } else if (grade == 5) {
                result = "fiveMoney";
            } else {
                result = "money";
            }
        }
        return result;
    }

    /**
     * 保存会员
     *
     * @param openId
     * @param unionId
     * @param orgId
     * @param name
     * @param heardUrl
     */
    public void saveMember(String openId, String unionId, String orgId, String name, String heardUrl, String parentId) {
        SaveMemberThread saveMemberThread = new SaveMemberThread();
        saveMemberThread.setOpenId(openId);
        saveMemberThread.setOrgId(orgId);
        saveMemberThread.setUnionId(unionId);
        saveMemberThread.setName(name);
        saveMemberThread.setHeardUrl(heardUrl);
        saveMemberThread.setParentId(parentId);
        saveMemberThread.run();
    }

    public ReturnData getMemberAddressService(String unionId, String orgId) {
        ReturnData returnData = new ReturnData();
        try {
            Record member = getMemberByunionId(unionId, orgId);
            String id = member.getStr("id");
            String sql = "SELECT *from yx_member_address where memberId='" + id + "'";
            Record record = Db.findFirst(sql);
            returnData.setCode("00000");
            returnData.setData(record);
            returnData.setMsg("请求成功");
        } catch (Exception e) {
            Syslog.error(e);
            returnData.setCode("00000");
            returnData.setMsg(e + "");
        }
        return returnData;
    }


    /**
     * 下单支付
     *
     * @param openId
     * @param orgId
     * @param unionId
     * @param commodityId
     * @param number
     * @return
     */

    public ReturnData payService(String openId, String orgId, String unionId, String commodityId, int number) {
        Record memberRecord = getMemberByunionId(unionId, orgId);
        int money = commodityMoneyByUnionId(unionId, commodityId, orgId);
        money = money * number;//总价格
        String orderId = UtilOrder.createOrder(Long.parseLong(orgId));
        Record commodity = getCommodityById(commodityId);
        String commodityName = commodity.getStr("name");
        Record orderRecord = new Record().set("id", orderId).set("money", money).set("memberId", memberRecord.getStr("id"))
                .set("orgId", orderId).set("createTime", new Date()).set("commodityId", commodityId).set("number", number);
        cache.setex(orderId, 60 * 30, orderRecord);//将订单信息放入缓存
        Record wxConfig = getWxConfigByOrgId(orgId, 0);
        Map<String, String> params = new HashMap<>();
        params.put("appid", wxConfig.getStr("appId"));
        params.put("mch_id", wxConfig.getStr("mch_id"));
        params.put("nonce_str", System.currentTimeMillis() + "");
        params.put("body", commodityName);
        params.put("out_trade_no", orderId);
        params.put("total_fee", money + "");
        params.put("notify_url", wxConfig.getStr("domain") + "/mobile/callBack");
        params.put("trade_type", "JSAPI");
        params.put("openid", openId);
        String paternerKey = "05134b1ba4254e9d98ccb44e04560807";
        String sign = PaymentKit.createSign(params, paternerKey);
        params.put("sign", sign);
        Syslog.info(params);
        String xmlStr = PaymentApi.pushOrder(params);
        Map<String, String> map = PaymentKit.xmlToMap(xmlStr);
        Syslog.info(map);

        /*h5签名*/
        Map h5Map = new HashMap();
        h5Map.put("appId", wxConfig.getStr("appId"));
        h5Map.put("timeStamp", (System.currentTimeMillis() / 1000) + "");
        h5Map.put("nonceStr", UtilUUID.getUUID());
        h5Map.put("package", "prepay_id=" + map.get("prepay_id"));
        h5Map.put("signType", "MD5");
        sign = PaymentKit.createSign(h5Map, paternerKey);
        String tempPackage = h5Map.get("package").toString();
        h5Map.remove("package");
        h5Map.put("package1", tempPackage);
        h5Map.put("paySign", sign);
        ReturnData returnData = new ReturnData();
        returnData.setData(h5Map);
        return returnData;
    }

    /**
     * 根据会员unionId，商品Id 查询出该商品对此会员的售价
     */
    public int commodityMoneyByUnionId(String unionId, String commodityId, String orgId) {
        String memberSql = "SELECT *from yx_member where unionId='" + unionId + "' and orgId='" + orgId + "'";
        Record memberRecord = Db.findFirst(memberSql);
        int memberGrade = memberRecord.getInt("grade");
        String sql = "SELECT *from shop_commodity where id='" + commodityId + "'";
        Record commodityRecord = Db.findFirst(sql);//查询出商品信息
        int money = 0;
        if (memberGrade == 0) {//原价
            money = commodityRecord.getInt("money");
        } else if (memberGrade == 1) {
            money = commodityRecord.getInt("oneMoney");
        } else if (memberGrade == 2) {
            money = commodityRecord.getInt("twoMoney");
        } else if (memberGrade == 3) {
            money = commodityRecord.getInt("threeMoney");
        } else if (memberGrade == 4) {
            money = commodityRecord.getInt("fourMoney");
        } else if (memberGrade == 5) {
            money = commodityRecord.getInt("fiveMoney");
        } else {
            Syslog.error("会员等级异常");
        }
        return money;
    }

    /**
     * 根据unionId查询会员信息
     */
    public Record getMemberByunionId(String unionId, String orgId) {
        String sql = "SELECT *from yx_member where unionId='" + unionId + "' and orgId='" + orgId + "'";
        Record member = Db.findFirstByCache("oneDay", MD5.md5(sql), sql);
        return member;
    }

    /**
     * 根据userId查会员信息
     */
    public Record getMemberByUserIdService(String userId) {

        String sql = "SELECT *from yx_member where userId='" + userId + "'";

        Record record = Db.findFirst(sql);



        if (StringUtils.isBlank(record.getStr("invitationNum"))){
            record.set("invitationNum",PcService.getInvitationNum());
            Db.update("yx_member","id",record);
        }

        if (record.get("realName")==null || "null".equals(record.get("realName")+"")){

            record.set("realName","");
        }

        if (record.get("alipayAccount")==null || "null".equals(record.get("alipayAccount")+"")){

            record.set("alipayAccount","");
        }

        return record;

    }

    /**
     * 根据商品ID查询商品信息
     */
    public Record getCommodityById(String commodityId) {
        String sql = "SELECT *from commodity where id='" + commodityId + "'";
        Record commodity = Db.findFirst(sql);
        return commodity;
    }

    /**
     * 根据商品ID查询商品信息
     */
    public Record getCommodityByIdCache(String commodityId) {
        String sql = "SELECT *from commodity where id='" + commodityId + "'";
        Record commodity = Db.findFirstByCache(MD5.md5(sql), "tenMinutes", sql);
        return commodity;
    }

    /**
     * 回调函数
     */
    public void callBackService(Map<String, String> map) {
        String out_trade_no = map.get("out_trade_no");//订单号
        String transaction_id = map.get("transaction_id");
        Record orderRecord = cache.get(out_trade_no);
        orderRecord.set("state", "1");
        orderRecord.set("wxId", transaction_id);
        boolean saveOrder = Db.save("yx_order", "id", orderRecord);
        if (saveOrder == false) {
            Syslog.error("微信回调，保存订单信息至数据库失败" + JsonUtil.getJsonStr(orderRecord));
        }
        String addressId = orderRecord.getStr("addressId");
        Record address = cache.get(addressId);
        boolean saveAddress = Db.save("yx_member_address", "id", address);
        if (saveAddress == false) {
            Syslog.error("微信回调，保存地址信息至数据库失败" + JsonUtil.getJsonStr(saveAddress));
        }
        String memberId = orderRecord.getStr("memberId");//会员Id
        String orgId = orderRecord.getStr("orgId");
        int money = orderRecord.getInt("money");
        String commodityId = orderRecord.getStr("commodityId");
        String orderId = orderRecord.getStr("id");
        Map threadMap = new HashMap();
        threadMap.put("commodityId", commodityId);
        threadMap.put("memberId", memberId);
        threadMap.put("orgId", orgId);
        threadMap.put("orderId", orderId);
        /*执行返利*/
        RebateThread rebateThread = new RebateThread(threadMap);
        Thread thread = new Thread(rebateThread);
        thread.start();
    }

    /**
     * 查询会员地址
     */
    public Record getMemberAddress(String memberId) {
        String sql = "SELECT *from yx_member_address where memberId='" + memberId + "'";
        Record record = Db.findFirst(sql);
        return record;
    }

    /**
     * 会员返利
     */
    public void memberRebate(String memberId, String orgId, double money) {
        String orgSql = "SELECT *from yx_rule where orgId='" + orgId + "' ORDER BY grade ";
        String sql = "SELECT *from yx_member_tree where memberId='" + memberId + "' ";
        Record record = Db.findFirst(sql);
        List<Record> list = Db.find(orgSql);
        for (int i = 0; i < list.size(); i++) {
            Record tempRecord = list.get(i);
            double grade = tempRecord.getDouble("grade");
            if (i == 0) {//一级返利
                String oneMemberId = record.getStr("oneParentId");
                String memberSql = "SELECT *from yx_member where id='" + oneMemberId + "'";
                Record memberRecord = Db.findFirstByCache("oneDay", MD5.md5(memberSql), memberSql);
                money = money * grade;//返利的金额
                int intMoney = (int) (money * 100);
                redPackService(intMoney, memberRecord.getStr("orgId"), memberRecord.getStr("openId"));
            } else if (i == 1) {
                String oneMemberId = record.getStr("twoParentId");
                String memberSql = "SELECT *from yx_member where id='" + oneMemberId + "'";
                Record memberRecord = Db.findFirstByCache("oneDay", MD5.md5(memberSql), memberSql);
                money = money * grade;//返利的金额
                int intMoney = (int) (money * 100);
                redPackService(intMoney, memberRecord.getStr("orgId"), memberRecord.getStr("openId"));
            } else if (i == 2) {
                String oneMemberId = record.getStr("threeParentId");
                String memberSql = "SELECT *from yx_member where id='" + oneMemberId + "'";
                Record memberRecord = Db.findFirstByCache("oneDay", MD5.md5(memberSql), memberSql);
                money = money * grade;//返利的金额
                int intMoney = (int) (money * 100);
                redPackService(intMoney, memberRecord.getStr("orgId"), memberRecord.getStr("openId"));
            } else if (i == 3) {
                String oneMemberId = record.getStr("fourParentId");
                String memberSql = "SELECT *from yx_member where id='" + oneMemberId + "'";
                Record memberRecord = Db.findFirstByCache("oneDay", MD5.md5(memberSql), memberSql);
                money = money * grade;//返利的金额
                int intMoney = (int) (money * 100);
                redPackService(intMoney, memberRecord.getStr("orgId"), memberRecord.getStr("openId"));
            } else if (i == 4) {
                String oneMemberId = record.getStr("fiveParentId");
                String memberSql = "SELECT *from yx_member where id='" + oneMemberId + "'";
                Record memberRecord = Db.findFirstByCache("oneDay", MD5.md5(memberSql), memberSql);
                money = money * grade;//返利的金额
                int intMoney = (int) (money * 100);
                redPackService(intMoney, memberRecord.getStr("orgId"), memberRecord.getStr("openId"));
            } else {
                Syslog.info("数据异常");
            }
        }

    }
    /**
     * 查询会员等级
     */


    /**
     * 返利红包
     *
     * @return
     */
    public void redPackService(int money, String orgId, String openId) {

        Record wxConfig = getWxConfigByOrgId(orgId, 0);
        Map<String, String> map = new HashMap<>();
        map.put("nonce_str", (System.currentTimeMillis() / 1000) + "");
        String id = UuidUtil.get32UUID().substring(8);
        map.put("mch_billno", id);
        map.put("mch_id", wxConfig.getStr("mch_id"));
        map.put("wxappid", wxConfig.getStr("appId"));
        map.put("send_name", "小乖购");
        map.put("re_openid", openId);
        map.put("total_amount", money + "");
        map.put("wishing", "推广多多，返利多多");
        map.put("client_ip", "127.0.0.1");
        map.put("act_name", "你是最棒的~，么么哒");
        map.put("total_num", "1");
        map.put("remark", "返利红包");
        String paternerKey = "05134b1ba4254e9d98ccb44e04560807";
        String sign = PaymentKit.createSign(map, paternerKey);
        map.put("sign", sign);
        String result = RedPackApi.sendRedPack(map, "D:\\dingyuankeji\\admin\\src\\main\\resources\\payFile\\apiclient_cert.p12", wxConfig.getStr("mch_id"));
        Syslog.info(result);
    }

    public static void main(String[] strings) {
        Map<String, String> map = new HashMap<>();
        map.put("nonce_str", (System.currentTimeMillis() / 1000) + "");
        String id = UuidUtil.get32UUID().substring(8);
        map.put("mch_billno", id);
        map.put("mch_id", "1491318292");
        map.put("wxappid", "wxeae06ad6f1ac729b");
        map.put("send_name", "馨冉国际");
        map.put("re_openid", "o3zbnwh25CGt6RSoCtjQ3g26mR7U");
        map.put("total_amount", "15000");
        map.put("wishing", "馨冉国际");
        map.put("client_ip", "127.0.0.1");
        map.put("act_name", "馨冉国际");
        map.put("total_num", "1");
        map.put("remark", "返利红包");
        String paternerKey = "05134b1ba4254e9d98ccb44e04560807";
        String sign = PaymentKit.createSign(map, paternerKey);
        map.put("sign", sign);
        String result = RedPackApi.sendRedPack(map, "D:\\dingyuankeji\\admin\\src\\main\\resources\\payFile\\apiclient_cert.p12", "1491318292");
        Syslog.info(result);

    }

    /**
     * 首页数据
     */
    public ReturnData indexDataService(String type) {

        Map map = new HashMap();
        /*轮播图*/
        List<Record> slideshowImg = getSlideshowimgService(type);

        map.put("slideshowImg", slideshowImg);

        /*类别*/

        List<Record> commodityClass = getAllCommodityClassService(type);

        map.put("commodityClass", commodityClass);

        /*公告*/

        List<Record> notes = getNoticeService(type);

        map.put("notes", notes);

        /*热门卡项*/

        List<Record> hotCommodityList = hotCommodityList(type);

        map.put("hotCommodityList", hotCommodityList);

        ReturnData returnData = new ReturnData(true);

        returnData.setData(map);

        return returnData;
    }

    /**
     * 保存卡项
     */
    public ReturnData saveCardService(Map<String, String[]> map, Map cacheMap) {
        ReturnData returnData = new ReturnData();

        Record memberInfo = (Record) cacheMap.get("memberInfo");
        String forbid=memberInfo.getStr("forbid");

        // 被拉黑
        if ("1".equals(forbid)){
            returnData.setResult(false);
            returnData.setMsg("您提交错误卡密次数太多，请联系客服。");
            return returnData;
        }

        Record parameters = MapToRecord.getRecord(map);
        // 有无卡号
        String hasCardNumber = parameters.getStr("hasCardNumber");


        parameters.remove("hasCardNumber");

        String type = parameters.getStr("type");

        parameters.remove("type");

        Date date = new Date();

        Record baseRecord = parameters;

        String memberId = memberInfo.getStr("id");

        String memberType=memberInfo.getStr("type");//会员类型

        //不是支付宝会员
        if ("2".equals(memberType)==false){
            if ("".equals(map.get("alipayAccount")[0])|| "".equals(map.get("realName")[0])){
                returnData.setResult(false);
                returnData.setMsg("请输入支付宝账户和真实姓名");
                return returnData;
            }
        }

        Db.update("update yx_member set realName=?,alipayAccount =? where id =?", map.get("realName")[0]
                , map.get("alipayAccount")[0], memberId);

        String orderId = DateUtil.getSdfTimes() + Tools.getRandomNum();

        baseRecord.set("memberId", memberId).set("orderId", orderId);

        boolean sa = false;

        String cardNumber = parameters.getStr("cardNumber");

        String cardPassword = parameters.getStr("cardPassword");

        String commodityId = parameters.getStr("commodityId");

        Record commodity = getCommodityByIdCache(commodityId);

        String comodityType=commodity.getStr("type");

        String feedbackId = parameters.getStr("feedbackId");

        Record faceValue = getFacevalueByIdCache(feedbackId);




        commodityId=faceValue.getStr("commodityId");

        Double rebatesThan=0.00;

        Record rebatesThanRecod = Db.findFirst("select rebatesThan from yx_member_rebates where memberId='" + memberInfo.getStr("id") + "'" +
                " and faceValueId='" + faceValue.getStr("id") + "'");
         if (rebatesThanRecod!=null){

             rebatesThan=Double.parseDouble(rebatesThanRecod.getStr("rebatesThan")) ;

         }else {

             Syslog.info(faceValue.toJson());

             rebatesThan=faceValue.getDouble("discount");

         }
        baseRecord.set("id", DateUtil.getSdfTimes() + Tools.getRandomNum())
                .set("createTime", date).set("classId", commodity.getStr("classId")).set("type",comodityType)
                .set("commodityId", commodity.getStr("id")).set("commodityName", commodity.getStr("name"))
                .set("feedbackId", feedbackId).set("feedbackValue", faceValue.get("faceValue"))
                .set("discount", rebatesThan).set("imgPath", commodity.get("imgPath"))
                .set("className", commodity.get("className")).remove("alipayAccount").remove("realName");


        if ("0".equals(type)) {//单卡提交

            parameters.remove("cards");

            Object objCardPass=cache.get("cardPassword"+cardPassword.trim()+cardNumber);

            if (objCardPass!=null){

                returnData.setResult(false);

                returnData.setMsg("卡密："+cardPassword.trim()+"已提交过，请勿重复提交");

                return returnData;
            }

            Record temp = baseRecord;
            if ("1".equals(hasCardNumber)) {

                Syslog.info("无卡号");

                temp.set("cardNumber", "").set("cardPassword", cardPassword.trim());
            } else {

                Syslog.info("有卡号");


                temp.set("cardNumber", cardNumber.trim()).set("cardPassword", cardPassword.trim());
            }
            sa = Db.save("card", "id", temp);

            if (!sa) {
                throw new RuntimeException();
            }else {

                //cache.setex("cardPassword"+cardPassword.trim(),60*60*24*30,cardPassword.trim());

            }

        } else {//批量提交


                String cards = parameters.getStr("cards");
//                    .replaceAll("，", ",")
//                    .replaceAll("\\s", ",");
//
//            Syslog.info("解析出来的卡密："+cards);

            baseRecord.remove("cards");

            String[] cardsArr = null;


            /*把不同的卡分隔开*/
            List<Record> cardList = new ArrayList<>();

            try {
                if ("0".equals(hasCardNumber)) {        //有卡号

                    cardsArr=cards.split("\n");

                    for (int i = 0; i < cardsArr.length; i++) {

                        String cardStr = cardsArr[i];

                        cardStr = cardStr
                    .replaceAll("，", ",")
                                .replace(" ",",")
                                .replace("\\s",",")
                                .replaceAll(" ",",")
                                .replace(" ",",");

                        Syslog.info("解析出来的卡密："+cardStr);


                        String[] cardArr = cardStr.split(",");

                        cardNumber = cardArr[0];

                        cardPassword = cardArr[1];

                        Record record = new Record().setColumns(baseRecord).set("cardNumber", cardNumber.trim())
                                .set("cardPassword", cardPassword.trim()).set("id", DateUtil.getSdfTimes() + Tools.getRandomNum());

                        cardList.add(record);


                        Object objCardPass=cache.get("cardPassword"+cardPassword.trim()+cardNumber);

                        if (objCardPass!=null){

                            returnData.setResult(false);

                            returnData.setMsg("卡密："+cardPassword.trim()+"已提交过，请勿重复提交");

                            return returnData;
                        }

                    }

                    int[] insert = Db.batchSave("card", cardList, cardList.size());

                    boolean check = BatchCheck.check(insert);

                    if (check == false) {
                        throw new RuntimeException();
                    }
                } else {        //无卡号
                    cardsArr = cards.split("\n");
                    for (int i = 0; i < cardsArr.length; i++) {

                        cardPassword = cardsArr[i];       //卡密


                        Record record = new Record().setColumns(baseRecord).set("cardNumber", "")
                                .set("cardPassword", cardPassword.trim()).set("id", DateUtil.getSdfTimes() + Tools.getRandomNum());

                        cardList.add(record);


                        Object objCardPass=cache.get("cardPassword"+cardPassword.trim());

                        if (objCardPass!=null){

                            if ("".equals(objCardPass.toString())==false){
                                returnData.setResult(false);

                                returnData.setMsg("卡密："+cardPassword.trim()+"已提交过，请勿重复提交");

                                return returnData;
                            }

                        }


                        //cache.setex("cardPassword"+cardPassword.trim(),60*60*24*30,cardPassword.trim());
                    }

                    int[] insert = Db.batchSave("card", cardList, cardList.size());

                    boolean check = BatchCheck.check(insert);

                    if (check == false) {
                        throw new RuntimeException();
                    }
                }
            } catch (Exception e) {

                Syslog.error("批量提交卡项格式错误：" + cards);

                returnData.setResult(false);

                returnData.setMsg("提交的数据格式错误");

                return returnData;

            }


        }

        /*保存订单*/

        Record orderRecord = new Record().set("id", orderId)
                .set("createTime", date).set("state", 0).set("memberId", memberId);

        boolean saveOrder = Db.save("order", "id", orderRecord);

        if (saveOrder == false) {
            throw new RuntimeException();
        } else {
            returnData.setResult(true);
//
//            Object send= cache.get("sendCard");
//            if (send==null){
//            }
        }
        /*根据orderId查询 卡密码*/
        String sql="SELECT *from card where orderId='"+orderId+"'";

        List<Record>  cards=Db.find(sql);

        for (int i=0;i<cards.size();i++){//遍历卡密码，防止重复提交

            try {
                Record temp=cards.get(i);

                String tempCardPassword=temp.getStr("cardPassword");

                cache.setex("cardPassword"+tempCardPassword.trim()+temp.getStr("cardNumber"),60*60*24*30,
                        tempCardPassword.trim());


            }catch (Exception e){

                Syslog.error(e);
            }


        }

        return returnData;
    }

    /**
     * 整理卡号
     */
    public ReturnData batchCardSettleService(Map<String,String[]> map){




        Record parameters = MapToRecord.getRecord(map);

        String commodityId=parameters.getStr("commodityId");

        Record commodity=Db.findFirst("SELECT *from commodity where id='"+commodityId+"'");




        String cards = parameters.getStr("cards").replace("，", ",")
                .replace(" ","").replaceAll("\t","");

        String[] cardArr=cards.split("\n");

        List<Record> cardList=new ArrayList<>();


        String hasCardNumber=parameters.getStr("hasCardNumber");//0有卡号 1无卡号

        int cardPasswordLength=commodity.getInt("cardPasswordSize");//卡密长度





        for (int i=0;i<cardArr.length;i++){

            Record card=new Record();

            String str=cardArr[i];

            if ("0".equals(hasCardNumber)){//有卡号

                int index=str.length()-cardPasswordLength;

                String cardNumber=str.substring(0,index);

                card.set("cardNumber",cardNumber);

                String cardPassword=str.substring(index);

                card.set("cardPassword",cardPassword);

                cardList.add(card);

            }else {//无卡号




            }




        }





        System.out.println(1233);


        return null;


    }

    /**
     * 读取图片中的卡号
     */

    public ReturnData readImgText(String filePath,String commodityId){


        ReturnData returnData=new ReturnData();

        String str=BDQrParse.numbers(filePath);

        if (str==null){

            returnData.setResult(false);

            returnData.setData("识别失败");

        }else {

            Record commodity=Db.findFirst("SELECT *from commodity where id='"+commodityId+"'");

            Record card=new Record().set("cardNumber","").set("cardPassword","");

            int cardPasswordLength=commodity.getInt("cardPasswordSize");//卡密长度

            int cardNumberSize=commodity.getInt("cardNumberSize");//卡号长度


            Map strMap= JsonUtil.getMapFromJsonObjStr(str);

            List words_resultList=JsonUtil.getListFromJsonArrStr(strMap.get("words_result").toString());




            for(int i=0;i<words_resultList.size();i++){


                Map temp= (Map) words_resultList.get(i);

                String words=temp.get("words").toString();


                if (words.length()==cardNumberSize){

                    card.set("cardNumber",words);


                }else if (words.length()==cardPasswordLength){

                    card.set("cardPassword",words);

                }


            }

            returnData.setResult(true);

            returnData.setData(card);

        }

        return returnData;

    }




    /**
     * 热门卡项
     */
    public List<Record> hotCommodityList(String type) {

        String sql = "SELECT *from commodity where hotNumber is not null and state !=3 and type='" +


                type + "' ORDER BY hotNumber ";

        List<Record> list = Db.find(sql);

        return list;

    }


    /**
     * 获取轮播图
     */
    public List<Record> getSlideshowimgService(String type) {

        String sql = "SELECT *from slideshowimg  where type='"+type+"' ORDER BY number";

        List<Record> list = Db.find(sql);

        return list;


    }

    /**
     * 获取所有商品类别
     */
    public List<Record> getAllCommodityClassService(String type) {

        String sql = "SELECT *from commodity_class  where state=0";
        if (StringUtils.isNotBlank(type))sql+=" and cType='"+type+"'";
        sql+="  ORDER BY number";

        List<Record> list = Db.find(sql);

        return list;

    }

    /**
     * 根据商品类别id查询商品
     */
    public List<Record> getCommodityByClassIdService(String classId, String type) {

        String sql = "SELECT *from commodity where state = 1 and classId='" + classId + "' and type='" + type + "' ";

        List<Record> list = Db.find(sql);

        return list;

    }

    /**
     * 根据商品id查询卡面值
     */
    public List<Record> getFaceValueService(String commodityId) {

        String sql = "SELECT *from commodity_facevalue  where commodityId='" + commodityId + "'" +
                " order by faceValue";

        List<Record> list = Db.find(sql);

        return list;

    }

    /**
     * 根据面值id查询面值
     */
    public Record getFacevalueByIdCache(String id) {

        String sql = "SELECT *from commodity_facevalue where id='" + id + "'";

        Record record = Db.findFirst( sql);

        return record;
    }


    /**
     * 获取所有的公告
     */
    public List<Record> getNoticeService(String type) {

        String sql = "SELECT * from notice where 1=1";
        sql+=" and type="+type;
        sql+="  ORDER BY createTime desc";
        List<Record> list = Db.find(sql);
        return list;

    }

    /**
     * 反馈
     */
    public ReturnData setAdvicefeedback(Map<String, String[]> map) {

        String id = UuidUtil.get32UUID();
        String title = map.get("title")[0];
        String content = map.get("content")[0];
        String phone = map.get("phone")[0];
        String type = map.get("type")[0];
        ReturnData we = new ReturnData();
        Date data = new Date();
        boolean red1 = true;

        Record record = new Record().set("id", id).set("title", title).set("content", content).set("phone", phone).set("createTime", data).set("type",type);
        red1 = Db.save("feedback", "id", record);


        if (red1) {

            we.setMsg("成功");
            we.setCode("000000");
            we.setResult(true);

        } else {

            we.setMsg("失败");
            we.setCode("111111");
            we.setResult(false);
        }
        return we;
    }

    /**
     * 根据id查公告
     *
     * @param id
     * @return
     */
    public Record getNoticeById(String id) {
        Record record = null;
        String sql = "SELECT * FROM notice WHERE id = '" + id + "'";
        record = Db.findFirst(sql);
        return record;
    }

    public static String getInvitationNum(){
        List<Object> invitationNumList = Db.query("select invitationNum from yx_member");
        String invNum=UuidUtil.get6UUID();
        Iterator<Object> iterator = invitationNumList.iterator();
        while(iterator.hasNext()){
            if (!invNum.equals(iterator.next()))break;
            invNum=UuidUtil.get6UUID();
        }
        return invNum;
    }

    /**
     * 注册   userCode和password
     *
     * @param map
     * @return
     */
    public ReturnData register(Map<String, String[]> map) {
        ReturnData rd = new ReturnData();//返回数据类型
        final String userCode = map.get("userCode")[0];
        final String password = map.get("password")[0];
        final String phone = map.get("phone")[0];

        final String type="7";

        String veri = map.get("veri")[0];

        String invitationNum[]=map.get("invitationNum");
        final String salt = UuidUtil.get6UUID();  //盐值
        final String userId = UuidUtil.get32UUID(); //随机生成的用户Id
        final String encodePassword = MD5.md5(password + salt); //password+salt 使用md加密后


        String sysVeri =String.valueOf(cache.get("register" + veri));//获取redis中的验证码
        if (sysVeri == null) {//验证码过期
            rd.setMsg("请重新获取验证码");
            rd.setCode("111111");
            rd.setResult(false);

        } else if (!sysVeri.equals(veri)) {//验证码不正确
            rd.setMsg("验证码错误");
            rd.setCode("111111");
            rd.setResult(false);

        } else if (sysVeri.equals(veri)) {//验证码正确
            //判断userCode与手机号是否唯一
            int flag = Db.queryInt("SELECT count(*) FROM sys_user WHERE 1=1  and ( userCode = '" + userCode + "'" + " or " + "phone='" + phone + "' )");


            if (flag != 0) {
                rd.setResult(false);
                rd.setCode("111111");
                rd.setMsg("账号已注册");

            } else {
                String parentId="";
                if (invitationNum!=null){
                    parentId = Db.queryStr("select id from yx_member where invitationNum='" + invitationNum[0] + "'");
                }
                String invNum=getInvitationNum();

                final String finalParentId = parentId;
                final String finalInvNum = invNum;

                final String strType=type;
                //开启事务
                Db.tx(new IAtom() {
                    @Override
                    public boolean run() throws SQLException {

                        String userNameRandom = phone;//生成一个随机名字
                        try {
                            Db.save("sys_user", new Record().set("id", userId).set("userName", userNameRandom)
                                    .set("userCode", userCode).set("password", encodePassword).set("salt", salt)
                                    .set("locked", 0).set("type", 2).set("phone", phone)

                            );

                            Db.save("yx_member", new Record().set("id", UuidUtil.get32UUID())
                                    .set("name", userNameRandom).set("userId", userId).set("tel", phone)
                                    .set("parentId", finalParentId).set("invitationNum", finalInvNum)
                                    .set("type",strType).set("source",type)
                            );

                        } catch (Exception e) {

                            Syslog.error(e);
                            return false;//回滚
                        }
                        return true;

                    }
                });
                rd.setMsg("注册成功");
                rd.setCode("000000");
                rd.setResult(true);
            }
        }

        return rd;

    }

    /**
     * 登录
     *
     * @param map userCode和password
     * @return ReturnData
     */
    public ReturnData loginService(Map<String, String[]> map) {
        String[] phone = map.get("phone");
        String[] userCode = map.get("userCode");
        String[] password = map.get("password");
        String verifiction[] = map.get("veri");//验证码
        String type = map.get("type")[0];     //用来判断是账号登录还是验证码登录
        ReturnData rd = new ReturnData();
        if ((type == "userCodeLogin" || "userCodeLogin".equalsIgnoreCase(type))) {//账号登录
            int flag = Db.queryInt("SELECT count(id) from sys_user where userCode = '" + userCode[0] + "'");
            if (flag == 0) {
                rd.setResult(false);
                rd.setCode("111111");
                rd.setMsg("用户不存在");
            } else {
                Record sysUser = Db.findFirst("SELECT * FROM sys_user WHERE userCode= '" + userCode[0] + "'");
                String salt = sysUser.get("salt");
                String encodePassword = sysUser.get("password");
                String newEncodePassword = MD5.md5(password[0] + salt);
                if (newEncodePassword.equals(encodePassword)) {
                    rd.setCode("000000");
                    rd.setMsg("登录成功");
                    rd.setResult(true);

                    String userId = sysUser.getStr("id");


                    Record memberInfo = getMemberByUserIdService(userId);

                    String token = AES.AESEncode(userId);

                    Map<String, Record> userMap = new HashMap<>();
                    userMap.put("userInfo", sysUser);

                    userMap.put("memberInfo", memberInfo);

                    cache.setex(token, 60 * 60 * 24, userMap);

                    rd.setData(token);

                } else {
                    rd.setResult(false);
                    rd.setCode("111111");
                    rd.setMsg("密码错误");
                }
            }

        } else if ((type == "phoneCodeLogin" || "phoneCodeLogin".equals(type)) && (verifiction != null) && phone != null) {//验证码登录

            String sysVeri = cache.get("login" + verifiction[0]).toString();//获取redis中的验证码
            if (sysVeri == null) {//验证码过期
                rd.setMsg("请重新获取验证码");
                rd.setCode("111111");
                rd.setResult(false);

            } else if (!sysVeri.equals(verifiction[0])) {//验证码不正确
                rd.setMsg("验证码错误");
                rd.setCode("111111");
                rd.setResult(false);

            } else if (sysVeri.equals(verifiction[0])) {//验证码正确

                //判断用户是否存在
                Record sysUser = Db.findFirst("SELECT * from sys_user where phone = '" + phone[0] + "'");
                if (sysUser == null) {
                    rd.setResult(false);
                    rd.setCode("111111");
                    rd.setMsg("用户不存在");
                } else {
                    rd.setResult(true);
                    rd.setCode("000000");
                    rd.setMsg("登录成功");

                    /*查询会员信息*/

                    String userId = sysUser.getStr("id");

                    Record memberInfo = getMemberByUserIdService(userId);

                    String token = AES.AESEncode(userId);

                    Map<String, Record> userMap = new HashMap<>();

                    userMap.put("userInfo", sysUser);

                    userMap.put("memberInfo", memberInfo);

                    cache.setex(token, 60 * 60 * 24, userMap);

                    rd.setData(token);


                }

            }

        }

        return rd;
    }

    /**
     * 生成验证码 保存到Redis 返回键名
     *
     * @param type
     * @return
     * @TODO将验证码发给用户
     */
    public ReturnData generateVeriCode(String type, String phone) {
        ReturnData rd = new ReturnData();

        int veri = Tools.getRandomNum();
        String key = type + veri;//键名为type+code
        cache.setex(key, 1800, veri);

        cache.setex("login"+veri, 1800, veri);


        rd.setResult(true);
        rd.setCode("000000");
        rd.setMsg("成功");

        String smsSignName = PropKit.get("smsSignName");
        String templateCode = PropKit.get("smsTemplateCode");

        AliSendRandomNum.send(phone, smsSignName,
                templateCode, "{\"code\":\"" + veri + "\"}");

        Syslog.info("redis中存的验证码:" + key);
        return rd;
    }


    /**
     * 修改密码
     */
    public ReturnData updatepassServices(String id, String passWord, String newPasswprd) {
        ReturnData returnData = new ReturnData();
        String Xianshi = "";
        String sql = "SELECT * from sys_user WHERE id='" + id + "'";
        Record asd = Db.findFirst(sql);
        String userCode = asd.getStr("id");//账号
        String pwd = asd.getStr("password");//密码
        String oldpwd = MD5.md5(passWord + asd.getStr("salt"));
        boolean fa;
        if (pwd.equals(oldpwd)) {
            String newpwd = MD5.md5(newPasswprd + asd.getStr("salt"));
            Record record = new Record().set("id", id).set("password", newpwd);
            fa = Db.update("sys_user", "id", record);
            if (fa) {
                returnData.setResult(true);
                returnData.setCode("true");
                Xianshi = "密码修改成功";
            } else {
                returnData.setResult(false);
                returnData.setCode("false");
                Xianshi = "密码修改失败";
            }
        } else {
            returnData.setResult(false);
            returnData.setCode(Xianshi);
            Xianshi = "原密码错误";
        }
        returnData.setMsg(Xianshi);
        return returnData;
    }


    /**
     * 实名认证
     */
    public ReturnData realNameServices(String name, String zhifubao) {
        ReturnData returnData = new ReturnData();
        String sql = "UPDATE yx_member set realName='" + name + "',alipayAccount='" + zhifubao + "' WHERE id='asd'";
        int i = Db.update(sql);
        if (i > 0) {
            returnData.setData("true");
            return returnData;
        } else {
            returnData.setData("false");
            return returnData;
        }
    }

    /**
     * 分页查询交易记录
     *
     * @param limit
     * @param page
     * @return
     */
    public PageUtil getTradeRecordList(Integer limit, Integer page, Record memberInfo, String cardState,String startDate,String endDate,String cardNum,String orderNum) {
        String sql = "select o.*,c.imgPath,(c.discount*c.feedbackValue) as money,c.commodityName,c.className,c.cardNumber,c.cardPassword,c.feedbackValue,c.discount,c.msg,c.state as cardState from card c  left join `order` o on o.id=c.orderId where o.memberId='" + memberInfo.get("id").toString() + "'";
        String countSql = "select  count(c.id) from card c left join `order` o on c.orderId =o.id where c.memberId='" + memberInfo.get("id").toString() + "'";
        if (cardState != null) {
            //0交易成功 1 交易失败 2 交易中
            switch (cardState) {
                case "0":
                    sql += " and (c.state= 4 or c.state=5)";
                    countSql += " and (c.state = 4 or c.state=5)";
                    break;
                case "1":
                    sql += " and (c.state = 3 or c.state = 6)";
                    countSql += " and  (c.state = 3 or c.state = 6)";
                    break;
                case "2":
                    sql += " and (c.state = 0 or c.state = 1 or c.state = 2)";
                    countSql += " and (c.state = 0 or c.state = 1 or c.state = 2)";
                    break;
                default:
                    break;

            }
        }
        if (StringUtils.isNotBlank(endDate)){
            sql+=" and date_format(o.createTime,'%Y-%m-%d') = '"+endDate+"'";
            countSql += " and date_format(o.createTime,'%Y-%m-%d') =  '"+endDate+"'";
        }
        if (StringUtils.isNotBlank(cardNum)){
            sql+=" and cardNumber like '%"+cardNum+"%'";
            countSql+=" and cardNumber like '%"+cardNum+"%'";
        }
        if (StringUtils.isNotBlank(orderNum)){
            sql+=" and o.id like '%"+orderNum+"%'";
            countSql+=" and o.id like '%"+orderNum+"%'";
        }
        sql += "   order by o.createTime desc";
        PageUtil pageUtil = new PageUtil(page, limit, sql, countSql);
        List<Record> dataList = pageUtil.getList();
        for (Record trade : dataList) {
            switch (trade.getStr("cardState")) {
                case "0":
                    trade.set("cardStr", "处理中");
                    break;
                case "1":
                    trade.set("cardStr", "处理中");
                    break;
                case "2":
                    trade.set("cardStr", "处理中");
                    break;
                case "3":
                    String msg=trade.getStr("msg");

                    if ("获取不到充值卡发行地区".equals(msg)
                        ||"非有效卡号".equals(msg)
                            ||"非有效卡号".equals(msg)
                            ||"非有效卡密".equals(msg)
                            ||"卡密码失效".equals(msg)
                            ||"卡密码错误".equals(msg)
                            ||"卡密错误".equals(msg)
                            || "请联系客服".equals(msg))
                    {
                        trade.set("cardStr", msg);
                    }else {
                        trade.set("cardStr", "交易失败");
                    }
                    trade.set("money", 0);

                    break;
                case "4":
                    trade.set("cardStr", "交易成功");

                    break;
                case "5":
                    trade.set("cardStr", "交易成功");
                    break;
                case "6":

                    msg=trade.getStr("msg");
                    if ("相同卡密正在处理中".equals(msg)||"获取不到充值卡发行地区".equals(msg)
                        ||"非有效卡号".equals(msg)
                        ||"非有效卡号".equals(msg)
                        ||"非有效卡密".equals(msg)
                        ||"卡密码失效".equals(msg)
                        ||"卡密码错误".equals(msg)
                        ||"卡密错误".equals(msg)
                        || "请联系客服".equals(msg)){
                        trade.set("cardStr", msg);
                    }else {
                        trade.set("cardStr", "交易失败");
                        trade.set("money", 0);
                    }

                    break;
            }
        }
        return pageUtil;
    }


    /**
     * 根据会员id修改支付宝账号,实名
     *
     * @param map
     * @return
     */
    public ReturnData updateAlipayAccount(Map<String, String[]> map, String token) {
        ReturnData rd = null;
        String id = map.get("id")[0];
        String alipayAccount = map.get("alipayAccount")[0];
        String realName = map.get("realName")[0];

        Record record=MapToRecord.getRecord(map);

        if (realName != null && !"".equals(realName) && alipayAccount != null && !"".equals(alipayAccount)) {
            String sql = "update yx_member set alipayAccount = '" + alipayAccount + "', realName='" + realName + "' where id='" + id + "'";
            int flag = Db.update(sql);
            if (flag == 1) {
                rd = new ReturnData(true);//修改成功
                String querySql = "select * from yx_member where id ='" + id + "'";//查询会员
                Record member = Db.findFirst(querySql);
                querySql = "select * from sys_user where id =(select userId from yx_member where id='" + id + "')";//查询user
                Record user = Db.findFirst(querySql);
                Map<String, Record> userMap = new HashMap<>();


                userMap.put("userInfo", user);

                userMap.put("memberInfo", member);

                cache.setex(token, 60 * 60 * 24, userMap);

            } else {
                rd = new ReturnData(false);//修改失败

            }

        } else {
            rd = new ReturnData(false);
        }
        return rd;
    }

    /**
     * 实名认证
     */
    public ReturnData realNameServices(String token, String name, String zhifu,String IDCardNumber,String cardImg,String cardImgReverse) throws AlipayApiException {
        Map<String, Record> map = cache.get(token);
        Record member = map.get("memberInfo");

        Syslog.info("用户信息》》》"+member.toJson());


        String id = member.get("id");
        ReturnData returnData = new ReturnData();

        String sql = "UPDATE yx_member set realName='" + name
                + "',alipayAccount='" + zhifu
                + "',cardImg='" + cardImg
                + "',cardImgReverse='" + cardImgReverse
                + "',IDCardNumber='"
                + IDCardNumber+ "' WHERE id='" + id + "'";
        int i = Db.update(sql);
        if (i > 0) {
            returnData.setCode("000000");
            member.set("realName", name).set("alipayAccount", zhifu).set("name",name);
            map.put("memberInfo", member);
            cache.setex(token, 60 * 60 * 24, map);
            returnData.setResult(true);


            ReturnData uriRet=AliyunBcprovUtil.cprovUtil(name,IDCardNumber,token);

            returnData.setData(uriRet.getData());

            return returnData;
        } else {
            returnData.setResult(false);
            return returnData;
        }
    }

    /**
     * 蜜蜂回调
     *
     * @param map
     * @return
     */
    public String mifengCallbackService(Map<String, String[]> map) {


        String resultStr="success";


        String state = map.get("state")[0];//回调结果  8失败，9成功

        String state_info = map.get("state_info")[0];//状态描述

        String amount=map.get("amount")[0];//处理面值



        String third_order_sn = map.get("attach")[0];//上送单号

        boolean myResult = false;//销卡结果 销卡成功或失败

        if ("9".equals(state)){

            myResult=true;

        }


        String sendSql = "SELECT *from card where id='" + third_order_sn + "'";

        Record card = Db.findFirst(sendSql);

        String feedbackValue=card.getStr("feedbackValue");//卡面值

        if (amount.equals(feedbackValue)==false && "9".equals(state)){//面值不符合


            Db.update(" update card set msg='销卡面值不符' , state=6   where id ='" + third_order_sn + "'");

            return resultStr;

        }

        String cardId = third_order_sn;

        String cardState = Db.queryStr("select state from card where id =?", cardId);



        if ("5".equals(cardState)==false){


            if (myResult == false) {//销卡失败

                Db.update(" update card set msg='" + state_info + "',state='3'    where id ='" + cardId + "'");

            }else {

                if ("1".equals(cardState) || "2".equals(cardState)) {

                    //查出来推卡记录的ID
                    String cardSendSql="select *from card_send_logs where cardId='"+third_order_sn+"' ";

                    Record log=Db.findFirst(cardSendSql);

                    updateCardState(log.getStr("id"), myResult);

                }

            }


        }else {

            Syslog.info("卡号："+cardId+"状态已经是成功状态，不再做修改");

        }

        return resultStr;

    }


    /**
     * 闲卡网回调
     *
     * @param map
     * @return
     */
    public Map xkCallbackService(Map<String, String[]> map) {



        String result = map.get("result")[0];//回调结果  1 成功 2 失败

        String order_type = map.get("order_type")[0];//1 卡片 2实物

        String order_sn = map.get("order_sn")[0];//平台单号

        String failed_msg = map.get("failed_msg")[0];//失败原因

        String third_order_sn = map.get("third_order_sn")[0];//上送单号

        boolean myResult = false;//销卡结果 销卡成功或失败

        boolean flag = true;

        myResult = "1".equals(result) ? true : false;

        String sendLog = "SELECT *from card_send_logs where id='" + third_order_sn + "'";

        Record cardLog = Db.findFirst(sendLog);

        String cardId = cardLog.getStr("cardId");

        String cardState = Db.queryStr("select state from card where id =?", cardId);

        Map<String, Object> resultMap = new HashMap<>();


        if ("5".equals(cardState)==false){

            if ("1".equals(cardState) || "2".equals(cardState)) {

                flag = updateCardState(third_order_sn, myResult);

            }

            if (myResult == false) {//销卡失败

                Db.update(" update card set msg='" + failed_msg + "'    where id ='" + cardId + "'");

            }


            if (flag) {
                resultMap.put("code", 1000);
                resultMap.put("msg", "success");
            } else {
                resultMap.put("code", 2000);
                resultMap.put("msg", "failed");
            }

        }else {

            Syslog.info("卡号："+cardId+"状态已经是成功状态，不再做修改");

        }

        return resultMap;

    }



    /**
     * 其他平台回调后修改订单状态 result true 为销卡成功,fasle为销卡失败
     *
     * @param cardSendLogsId //上传记录ID
     */
    public boolean updateCardState(String cardSendLogsId, boolean result) {
        boolean flag = true;
        Record cardSendLog = Db.findFirst("select * from card_send_logs where id=?", cardSendLogsId);
        Record card = Db.findFirst("select * from card where id =?", cardSendLog.getStr("cardId"));
        Record member = Db.findFirst("select * from yx_member where id=?", card.getStr("memberId"));

        if (cardSendLog == null) {
            return false;       //如果未查到记录,返回false
        }
        if (result) { //销卡成功

            Syslog.info("上送Id:" + cardSendLogsId + "  销卡成功，开始支付");

            String amount = Db.queryStr("select cast(discount*feedbackValue as decimal(10,2)) from card where id=?", cardSendLog.getStr("cardId"));
            String payNum=Db.queryStr("select count(id) from apply_logs where cardId =? and (returnCode='000000' or returnCode='0' or returnCode='10000')",card.getStr("id"));

            ReturnData payResult =new ReturnData(false) ;
                if(("0").equals(payNum)){        //如果未曾支付成功过,则支付
                   payResult = toPaybyCardId(card.getStr("id"), amount);
                }

            if (payResult.isResult()) {   //支付成功

                Syslog.info("上送Id:" + cardSendLogsId + "  支付成功");


                Db.update(" update `order` set state = 2 where id =?", cardSendLog.getStr("orderId"));

                Db.update("update card set state =5,payState=1,payTime=now(), msg='已付款' where id=?", cardSendLog.getStr("cardId"));

                Record applyLog = new Record().set("id", UuidUtil.get32UUID()).set("realName", member.getStr("realName"))
                        .set("applyAccount", member.getStr("alipayAccount")).set("money", amount)
                        .set("cardId", card.getStr("id")).set("orderId", card.getStr("orderId")).set("memberId", member.getStr("id"))
                        .set("createTime", DateUtil.getTime()).set("returnCode", "000000").set("returnMsg", payResult.getMsg())
                        .set("returnJson", payResult.getMsg()).remove("msg");

                Db.save("apply_logs", "id", applyLog);

                Record memberAccountLog = applyLog.remove("returnJson").remove("returnMsg").remove("returnCode").remove("cardId")
                        .remove("id");

                memberAccountLog.set("id", UuidUtil.get32UUID()).set("code", payResult.getCode()).set("msg", payResult.getMsg());

                Db.save("member_account_logs", "id", memberAccountLog);

            } else {  //支付失败

                Syslog.info("上送Id:" + cardSendLogsId + "  支付失败");

                Db.update("update  `order` set state = 1  where id =?", card.getStr("orderId"));

                Db.update("update card set payState = 2, msg='销卡成功，支付失败'  where id =?", card.getStr("id"));


                Record applyLog = new Record().set("id", UuidUtil.get32UUID()).set("realName", member.getStr("realName"))
                        .set("applyAccount", member.getStr("alipayAccount")).set("money", amount)
                        .set("cardId", card.getStr("id")).set("orderId", card.getStr("orderId")).set("memberId", member.getStr("id"))
                        .set("createTime", DateUtil.getTime()).set("returnCode", payResult.getCode()).set("returnMsg", payResult.getMsg())
                        .set("returnJson", payResult.getMsg()).remove("msg");

                Db.save("apply_logs", "id", applyLog);

            }

        } else {  //销卡失败

            Syslog.info("上送Id:" + cardSendLogsId + "  销卡失败");

            Db.update("update `order` set state = 3 where id =? ", card.getStr("orderId"));

            Db.update(" update card set state = 6 ,payState =0   where id =?", card.getStr("id"));
        }
        return flag;
    }

    /**
     * 通过cardId付款
     *
     * @param cardId
     * @return
     */
    private ReturnData toPaybyCardId(String cardId, String amount) {

        Syslog.info("通过卡id向支付宝付款：" + cardId);

        ReturnData rd = new ReturnData();

        try {
            Record card = Db.findFirst("select * from card where id=?", cardId);


            Record member = Db.findFirst("select * from yx_member where id=?", card.getStr("memberId"));

            Map<String, String> map = new HashMap<>();

            /*支付宝转账*/
            if ("2".equals(member.getStr("type"))) {//支付宝会员具有支付宝userId

                Syslog.info("通过userId向个人转账");

                map.put("payee_type", "ALIPAY_USERID");
                map.put("payee_account", member.getStr("alipayId"));
            } else {
                Syslog.info("通过真实姓名，支付宝保定账户向个人转账");
                map.put("payee_type", "ALIPAY_LOGONID");
                map.put("payee_account", member.getStr("alipayAccount"));
                map.put("payee_real_name", member.getStr("realName"));
            }

            //参数
            map.put("amount", amount);
            map.put("payee_real_name", member.getStr("realName"));
            map.put("remark", card.getStr("cardNumber") + "_" + amount);

            map.put("cardId",card.getStr("cardNumber"));

            Syslog.info("支付参数:" + map);

            AlipayFundTransToaccountTransferResponse response = null;//返回结果
            try {
                response = AlipayUtil.pay(map);

                Syslog.info(response.getBody());

            } catch (Exception e) {
                Syslog.error(e);
            }
            if (response != null) {
                if (response.isSuccess()) {
                    rd.setMsg(response.getMsg());
                    rd.setCode(response.getCode());
                    rd.setResult(true);
                } else {
                    rd.setMsg(response.getBody());
                    rd.setCode(response.getCode());
                    rd.setResult(false);
                }
                Syslog.info("支付结果:" + response.getMsg());
            } else {
                rd.setResult(false);
                rd.setMsg("支付失败");

            }
        } catch (Exception e) {

            Syslog.error(e);
            rd.setResult(false);
        }
        return rd;

    }

    /**
     * 收卡啦回调
     */
    public String skCallbackService(Map<String, Object> map) {

        String cardStatus = map.get("cardStatus").toString();

        String msg = ApiReturn.getMsgByCode(cardStatus, "3");

        String userOrderNo = map.get("userOrderNo").toString();
        boolean myResult = false;   //是否销卡成功
        boolean flag = false;

        String cardId = Db.queryStr("select cardId from card_send_logs where id =?", userOrderNo);
        int cardState = Db.queryInt("select state from card where id =?", cardId);

        if (cardState==5){//已经成功状态
            Syslog.info("卡已经成功，不做修改"+userOrderNo);
        }else {
            if ("2011".equals(cardStatus)) {
                myResult = true;
            } else {
                myResult = false;
                /*销卡失败*/
                Syslog.info("收卡啦销卡失败:返回结果为" + JsonUtil.getJsonStr(map));

                String sql = "select *from card where id='" + cardId + "'";

                Record card = Db.findFirst(sql);

                card.set("msg", msg);
                if ("2013".equals(cardStatus) || "2014".equals(cardStatus)){
                    card.set("state", 6);//异常订单
                }else {

                    card.set("state", 3);//失败订单
                }

                Db.update("card", "id", card);

            }

            if (cardState == 1 || cardState == 2) {
                flag = updateCardState(userOrderNo, myResult);
            } else {
                return "okay";
            }
        }

        String returnResult = "success";
        if (!flag) returnResult = "failed";
        return returnResult;
    }




    /**
     * 易缴费回调
     */
    public String yjfCallbackService(Map<String, String[]> map)  {

        /*易缴费回调参数*/
        Syslog.info("易缴费回调参数");

        //String url="http://wxapplet.19xw.net/mobile/yjfCallback";

        final Map<String,String>  par=new HashMap<>();

        for (Map.Entry<String, String[]> entry : map.entrySet()) {
            //Map.entry<Integer,String> 映射项（键-值对）  有几个方法：用上面的名字entry
            //entry.getKey() ;entry.getValue(); entry.setValue();
            //map.entrySet()  返回此映射中包含的映射关系的 Set视图。
            Syslog.info("key= " + entry.getKey() + " and value= "
                    + entry.getValue()[0]);
            String value="";

            try {


                value=URLEncoder.encode(entry.getValue()[0],"utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

            par.put(entry.getKey(),value);
        }

        String orderId = map.get("orderId")[0];//用户id

        String status = map.get("state")[0];//订单状态 订单状态，SUCCESS，FAIL

        String returnCode = map.get("failReason")[0];//返回码

        String returnInfo = map.get("failExplain")[0];//返回描述

        String cardId = Db.queryStr("select cardId from card_send_logs where id =?", orderId);

        if (cardId != null) {//有此卡

            String sql = "select *from card where id='" + cardId + "'";

            Record card = Db.findFirst(sql);

            if (card.getInt("state") != 5) {

                Syslog.info("开启易缴费回调："+card.toJson());

                if ("SUCCESS".equalsIgnoreCase(status)) {//销卡成功

                    boolean flag = updateCardState(orderId, true);

                } else {

                    Syslog.info("易缴费:返回结果为" + JsonUtil.getJsonStr(MapToRecord.getRecord(map)));

                    card.set("msg", returnInfo).set("state", 3);

                    Db.update("card", "id", card);
                }

            } else {
                Syslog.info("卡号" + cardId + "已经是成功状态，不做修改");
            }
            return "OK";
        } else {


            return "OK";
        }

    }
    /**
     * 速销卡回调
     */
    public String sxkCallBackService(Record record){

        String orderId = record.get("orderId");//订单ID

        String status = record.getStr("status");//状态（1：处理中、2：成功、3：失败4：手动处理）判断订单的状态请使用这个字段！\

        String code=record.getStr("code");

        String successAmountStr=record.getStr("successAmount");//结算面值

        String memo = record.getStr("memo");//订单信息

        String cardId = Db.queryStr("select cardId from card_send_logs where id =?", orderId);

        String sql = "select *from card where id='" + cardId + "'";

        Record card = Db.findFirst(sql);

        if (card.getDouble("feedbackValue")!=Double.parseDouble(successAmountStr)){//销卡面值不符

            card.set("msg", "面值不符合，销卡失败")
                    .set("state", 3);

            Db.update("card", "id", card);


            return "Y";
        }




        if (card.getInt("state")!=5){

            if ("2".equalsIgnoreCase(status)) {//销卡成功

                boolean flag = updateCardState(orderId, true);

            } else {

                if ("000048".equals(code)){

                    card.set("state", 6);
                }else {
                    card.set("state", 3);
                }

                card.set("msg", memo);

                Db.update("card", "id", card);
            }

        }else {
            Syslog.info("卡号"+cardId+"已经是成功状态，不做修改");
        }

        return "Y";

    }





    /**
     * 通过类别ID查询类别
     */
    public Record getClassInfoById(String id) {

        String sql = "SELECT *from commodity_class where id='" + id + "'";

        Record record = Db.findFirst(sql);

        return record;
    }

    /**
     * 根据面值id对应商品判断有无卡号
     *
     * @param feedbackId
     * @return
     */
    public ReturnData hasCardNumberByFeedBackId(String feedbackId) {
        ReturnData rd = new ReturnData();
        Record facevalue = Db.findFirst("select * from commodity_facevalue where id=?", feedbackId);
        String queryApiType = "select apiType from commodity_facevalue where id=? and number=(select min(number) from commodity_xianka where commodityId=?)";
        String apiType = Db.queryStr(queryApiType, feedbackId, facevalue.getStr("commodityId"));
        // if(api)
        String querySql = "";
        String hasCardNumber = Db.queryStr(querySql);
        return rd;

    }

    /**
     * 余额统计
     */
    public ReturnData balanceStatistical(Record memberInfo) {
        String sql = "select sum(c.discount*c.feedbackValue) as money from card c  left join `order` o on o.id=c.orderId where" +
                " DATE_FORMAT(c.createTime,'%Y-%m-%d')=DATE_FORMAT(now(),'%Y-%m-%d') and o.memberId='" + memberInfo.get("id").toString() + "'";
        //BigDecimal dealing = Db.queryBigDecimal(sql + " and (c.state = 0 or c.state = 1)");//交易中
        //BigDecimal withdrawal=Db.queryBigDecimal(sql+" and c.state = 2");//提现中
        BigDecimal deal=Db.queryBigDecimal(sql+" and (c.state= 4 or c.state=5)");//交易成功
        ReturnData returnData=new ReturnData(true);

        String countSql="SELECT count(*) from card where DATE_FORMAT(createTime,'%Y-%m-%d')=DATE_FORMAT(now(),'%Y-%m-%d') and  memberId='"
                +memberInfo.getStr("id")+"' and state in ( ";
        /*会员成功笔数*/
        int cgbs=Db.queryInt(countSql+" '5' )");

        /*会员失败笔数*/

        int sbbs=Db.queryInt(countSql+" '3' )");

        /*会员处理中笔数*/
        int chulizhong=Db.queryInt(countSql+" '0','1','2','6','7' )");

        Record record=new Record()
                //.set("dealing",dealing)
                //.set("withdrawal",withdrawal)
                .set("deal",deal)
                .set("cgbs",cgbs).set("sbbs",sbbs).set("chulizhong",chulizhong).set("totalToday", cgbs + sbbs + chulizhong);

        returnData.setData(record);
        return returnData;
    }

    /**
     * 更改手机号
     */
    public ReturnData updatePhone(Map<String, String[]> map,String token) {
        ReturnData returnData=new ReturnData();
        Map<String, Record> tokenMap = cache.get(token);
        Record memberInfo = tokenMap.get("memberInfo");
        Record userInfo = tokenMap.get("userInfo");
        Record record = MapToRecord.getRecord(map);
        String phone=record.getStr("phone");
        String veri=record.getStr("veri");
        String sysVeri = cache.get("phone" + veri).toString();//获取redis中的验证码
        if (sysVeri == null) {//验证码过期
            returnData.setMsg("请重新获取验证码");
            returnData.setCode("111111");
            returnData.setResult(false);

        } else if (!sysVeri.equals(veri)) {//验证码不正确
            returnData.setMsg("验证码错误");
            returnData.setCode("111111");
            returnData.setResult(false);

        } else if (sysVeri.equals(veri)) {//验证码正确
            int flag = Db.queryInt("SELECT count(*) FROM sys_user WHERE type=2  and phone='" + phone + "'");

            if (flag != 0) {
                returnData.setResult(false);
                returnData.setCode("111111");
                returnData.setMsg("该手机号已绑定");
            } else {
                int update = Db.update("update sys_user set phone='"+phone+"' where id='"+userInfo.getStr("id")+"'");
                int update1 = Db.update("update yx_member set tel='" + phone + "' where id='" + memberInfo.getStr("id") + "'");
                if (update==1&&update1==1){
                    userInfo.set("phone",phone);
                    memberInfo.set("tel",phone);
                    tokenMap.put("userInfo",userInfo);
                    tokenMap.put("memberInfo",memberInfo);
                    cache.setex(token,60 * 60 * 24,tokenMap);
                    returnData.setResult(true);
                    returnData.setMsg("修改成功");
                }else{
                    returnData.setResult(false);
                    returnData.setCode("111111");
                    returnData.setMsg("修改失败");
                }
            }
        }
        return returnData;
    }

    /**
     * 公告列表PC端
     */
    public ReturnData noticeListPc(String page, String size,String type) {
        ReturnData returnData=new ReturnData();
        String sql="SELECT *from notice where 1=1";
        if (StringUtils.isNotBlank(type))sql+=" and type="+type;
        sql+=" ORDER BY createTime desc";
        PageUtil pageUtil=new PageUtil(Integer.parseInt(page),Integer.parseInt(size),sql);
        if (null!=pageUtil.getList()){
            returnData.setResult(true);
        }else{
            returnData.setResult(false);
            returnData.setMsg("暂无数据");
        }
        returnData.setData(pageUtil);
        return returnData;
    }

    /**
     * 转账记录
     */
    public ReturnData accountLog(String token, Map<String, String[]> map) {
        ReturnData returnData=new ReturnData();
        Record record = MapToRecord.getRecord(map);
        String startDate = StringUtils.isNotBlank(record.getStr("startDate"))?record.getStr("startDate"):DateUtil.getDayMinus(DateUtil.getDay(),30l);
        String endDate = StringUtils.isNotBlank(record.getStr("endDate"))?record.getStr("endDate"):DateUtil.getDay();
        String page = StringUtils.isNotBlank(record.getStr("page"))?record.getStr("page"):"1";
        String size = StringUtils.isNotBlank(record.getStr("size"))?record.getStr("size"):"10";
        String cardNum=record.getStr("cardNum");
        String orderNum=record.getStr("orderNum");
        Map<String,Record> recordMap= cache.get(token);
        String sql="select a.*,b.commodityName,b.cardPassword from member_account_logs a " +
                "LEFT JOIN card b on a.orderId=b.orderId where a.memberId='"+recordMap.get("memberInfo").getStr("id")+"'" +
                " and date_format(a.createTime,'%Y-%m-%d') between '"+startDate+"' and '"+endDate+"'";
        if (StringUtils.isNotBlank(cardNum))sql+=" and b.cardNumber like '%"+cardNum+"%'";
        if (StringUtils.isNotBlank(orderNum))sql+=" and b.orderId like '%"+orderNum+"%'";
        PageUtil pageUtil=new PageUtil(Integer.parseInt(page),Integer.parseInt(size),sql);
        if (null!=pageUtil.getList()){
            returnData.setResult(true);
        }else{
            returnData.setResult(false);
            returnData.setMsg("暂无数据");
        }
        returnData.setData(pageUtil);
        return returnData;
    }

    /**
     * 获取返利记录
     */
    public ReturnData getRebateLog(String userId) {


        try {

        }catch (Exception e){




        }

        ReturnData returnData=new ReturnData();
        String today=new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String moneySql="select if(a.summoney is null,0,a.summoney) summoney,if(b.todaymoney is null,0,b.todaymoney) todaymoney,if(c.yesterdaymoney is null,0,c.yesterdaymoney) yesterdaymoney from " +
                "(select SUM(rebateMoney) summoney from rebatelog) a join " +
                "(select SUM(rebateMoney) todaymoney from rebatelog where DATE_FORMAT(createTime,'%Y-%m-%d')='"+today+"') b join" +
                "(select SUM(rebateMoney) yesterdaymoney from rebatelog where DATE_FORMAT(createTime,'%Y-%m-%d')='2019-12-29') c";
        Record first = Db.findFirst(moneySql);
        String sql="select * from rebatelog where parentId='"+userId+"'";
        List<Record> list = Db.find(sql);
        if (list!=null&&list.size()>0){
            returnData.setResult(true);
            returnData.setData(new Record().set("list",list).set("money",first));
        }else{
            returnData.setResult(true);
            returnData.setMsg("暂无记录");
        }
        return returnData;
    }

    /**
     * 提现
     */
    @Before(Tx.class)
    public ReturnData withdrawDeposit(String token,Map map,String amount)throws Exception {
        Record memberInfo = (Record) map.get("memberInfo");
        ReturnData returnData=new ReturnData();
        BigDecimal a=new BigDecimal(memberInfo.getStr("rebateMoney"));
        BigDecimal b=new BigDecimal(amount);
        if (a.compareTo(b)>=0){
            boolean save = Db.save("withdrawLog", new Record().set("id", UuidUtil.get32UUID()).set("money", amount).set("state", "0")
                    .set("realName", memberInfo.getStr("realName")).set("memberId", memberInfo.getStr("id")));
            if (save){
                boolean update = Db.update("yx_member", "id", new Record().set("id", memberInfo.getStr("id")).set("rebateMoney", a.subtract(b)));
                map.put("memberInfo",memberInfo.set("rebateMoney",a.subtract(b)));
                cache.setex(token,60 * 60 * 24,map);
                if (!update)throw new Exception("修改返利余额异常");
                returnData.setResult(true);
                returnData.setMsg("提现成功");
            }else{
                throw new Exception("保存提现记录异常");
            }
        }else {
            returnData.setResult(false);
            returnData.setMsg("余额不足！");
        }
        return returnData;
    }

    /**
     * 获取提现记录
     */
    public ReturnData withdrawLogList(Record memberInfo,String state) {
        ReturnData returnData=new ReturnData();
        String sql="select * from withdrawLog where memberId='"+memberInfo.getStr("id")+"'";
        if (StringUtils.isNotBlank(state))sql+=" and state="+state;
        sql+=" order by updateTime desc";
        List<Record> list = Db.find(sql);
        if (list!=null&&list.size()>0){
            returnData.setResult(true);
            returnData.setData(list);
        }else{
            returnData.setResult(false);
            returnData.setMsg("暂无数据");
        }
        return returnData;
    }
}
